﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;

namespace CPPEI.Coolzon.Designer.DeployTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool ChangeWindowMessageFilter(uint message, uint dwFlag);

        uint WM_DROPFILES = 0x0233;
        uint WM_COPYDATA = 0x4A;
        uint MSGFLT_ADD = 1;

        private string solutionId;
        private string solutionName;
        private Version fileVersion;
        private Version fileRuntimeVersion;
        private string Type = "SHOW";
        private bool hasDropedFile = false;
        private string zipFileName;
        public MainWindow()
        {
            InitializeComponent();
            //解决管理员权限下无法拖拽问题，win7下有效，win10下无效
            ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD);
            ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
            ChangeWindowMessageFilter(0x0049, MSGFLT_ADD);
        }

        private void _dataGrid_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                zipFileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                AnalysisZipFile();
            }
        }

        private void AnalysisZipFile()
        {
            if (File.Exists(zipFileName))
            {
                solutionName = System.IO.Path.GetFileNameWithoutExtension(zipFileName);
                string solutionText;
                List<string> fileNames = PackageUtil.UnZipFileNames(zipFileName, null, out solutionText);
                _dataGrid.ItemsSource = fileNames;
                if (fileNames == null || fileNames.Count == 0 || string.IsNullOrWhiteSpace(solutionText))
                {
                    hasDropedFile = false;
                }
                else
                {
                    hasDropedFile = true;
                }

                ParseSolution(solutionText);
                button.Visibility = Visibility.Collapsed;
            }
            else
            {
                button.Visibility = Visibility.Visible;
                MessageBox.Show("文件不存在");
            }
        }

        private void ParseSolution(string solutionText)
        {
            XDocument xDoc = XDocument.Parse(solutionText);
            if (xDoc == null)
            {
                return;
            }

            XElement xSolution = xDoc.Root;

            if (xSolution.Attribute("Name") != null && !string.IsNullOrEmpty(xSolution.Attribute("Name").Value))
            {
                _name.Text = solutionId = xSolution.Attribute("Name").Value;
            }
            if (xSolution.Attribute("Caption") != null && !string.IsNullOrEmpty(xSolution.Attribute("Caption").Value))
            {
                _caption.Text = solutionName = xSolution.Attribute("Caption").Value;
            }
            if (xSolution.Attribute("Version") != null && !string.IsNullOrEmpty(xSolution.Attribute("Version").Value))
            {
                fileVersion = new Version(xSolution.Attribute("Version").Value);
                _version.Text = fileVersion.ToString();
            }
            if (xSolution.Attribute("RuntimeVersion") != null && !string.IsNullOrEmpty(xSolution.Attribute("RuntimeVersion").Value))
            {
                fileRuntimeVersion = new Version(xSolution.Attribute("RuntimeVersion").Value);
                _runtimeVersion.Text = fileRuntimeVersion.ToString();
            }
            if (xSolution.Attribute("Type") != null && !string.IsNullOrEmpty(xSolution.Attribute("Type").Value))
            {
                _type.Text = Type = xSolution.Attribute("Type").Value;
            }
        }

        private void _selectServerDirectory_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBD = new System.Windows.Forms.FolderBrowserDialog();
            if (folderBD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (folderBD.SelectedPath != string.Empty)
                {
                    _directory.Text = string.Format("{0}\\", folderBD.SelectedPath);
                    //if (File.Exists(string.Format("{0}\\Metadata\\Solution\\Solution.xml", folderBD.SelectedPath)))
                    //{
                    //}
                    //else
                    //{
                    //    MessageBox.Show("服务器目录");
                    //}
                }
            }
        }

        private void _deploy_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_directory.Text) || string.Equals(_directory.Text, "请选择服务器目录"))
            {
                MessageBox.Show("请选择服务器目录");
                return;
            }
            if (!hasDropedFile)
            {
                MessageBox.Show("请拖放发布文件");
                return;
            }
            string filename = string.Format("{0}\\Solution.xml", _directory.Text);
            string dir = string.Format("{0}\\", _directory.Text);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            XmlDocument xDoc = new XmlDocument();
            XmlNode xSolutionList = null;
            if (!File.Exists(filename))
            {
                XmlDeclaration dec = xDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xDoc.AppendChild(dec);
                xSolutionList = xDoc.CreateElement("Solution-List");
                xDoc.AppendChild(xSolutionList);
            }
            else
            {
                xDoc.Load(filename);
                xSolutionList = xDoc.SelectSingleNode("Solution-List");
            }
            XmlElement solution = xDoc.CreateElement("Solution");
            XmlAttribute xName = xDoc.CreateAttribute("Name");
            xName.Value = solutionId;

            XmlAttribute xCaption = xDoc.CreateAttribute("Caption");
            xCaption.Value = solutionName;

            XmlAttribute xVersion = xDoc.CreateAttribute("Version");
            xVersion.Value = fileVersion != null ? fileVersion.ToString() : string.Empty;

            XmlAttribute xRuntimeVersion = xDoc.CreateAttribute("RuntimeVersion");
            xVersion.Value = fileRuntimeVersion != null ? fileRuntimeVersion.ToString() : string.Empty;

            XmlAttribute xType = xDoc.CreateAttribute("Type");
            xType.Value = Type;

            solution.Attributes.Append(xName);
            solution.Attributes.Append(xCaption);
            solution.Attributes.Append(xVersion);
            solution.Attributes.Append(xRuntimeVersion);
            solution.Attributes.Append(xType);
            XmlNodeList xmlList = xSolutionList.SelectNodes(string.Format("//Solution[@Name='{0}']", solutionId));
            if (xmlList.Count > 0)
            {
                foreach(XmlNode node in xmlList)
                {
                    xSolutionList.RemoveChild(node);
                }
            }
            xSolutionList.AppendChild(solution);
            xDoc.Save(filename);
            if(PackageUtil.UnZip(zipFileName, dir))
            {
                MessageBox.Show("部署成功");
            }
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.RestoreDirectory = true;
            System.Windows.Forms.DialogResult result = System.Windows.Forms.DialogResult.Cancel;
            System.Windows.Application.Current.Dispatcher.Invoke(() => { result = fileDialog.ShowDialog(); });

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                zipFileName = fileDialog.FileName;
                AnalysisZipFile();
            }
        }
    }
}
